package com.hotel.homehotel.before.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotel.homehotel.before.entiy.JwtUser;
import com.hotel.homehotel.before.entiy.Role;
import com.hotel.homehotel.before.entiy.User;
import com.hotel.homehotel.before.mapper.RoleMapper;
import com.hotel.homehotel.before.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
//    PermissionMapper permissionMapper;
    RoleMapper roleMapper;
    @Resource
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String phoneNumber) throws UsernameNotFoundException {

//        if (user == null) {
//            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
//        }else {
        //查找用户密码
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("phone_number",phoneNumber);
        User user = userMapper.selectOne(queryWrapper);
        //查找角色
        List<Role> roles=roleMapper.getRoleMapperByPhoneNumber(phoneNumber);
        System.out.println(roles);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for ( Role role : roles) {
            authorities.add(new SimpleGrantedAuthority("ROLE_"+role.getName()));
            System.out.println("ROLE_"+role.getName());
        }
        System.out.println("kkkkkk      "+   roles);
//            System.out.println("loadUserByUsername......user ===> " + user);
        return new JwtUser(phoneNumber,user.getPassword(),authorities);
//        }

    }
}
